package com.monkey.luffer.springboot.demo.basis.example;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: dengkaibing
 * @Description:
 * @Date: 2020/12/22 15:01
 * @company 甜橙金融
 * @Version: 1.0
 */
@Slf4j
@Component
public class Student implements InitializingBean {
    //对于@Autowired声明的数组、集合类型，spring并不是根据beanName去找容器中对应的bean，而是把容器中所有类型与集合（数组）中元素类型相同的bean构造出一个对应集合，注入到目标bean中
    @Autowired
    private List<QueryService> list;

    private Map<String, QueryService> map = new HashMap<>();


    /**
     * 获取实例
     *
     * @param classType
     * @return
     */
    public QueryService getInstance(String classType) {
        if (!map.containsKey(classType)) {
            throw new IllegalArgumentException();
        }
        return map.get(classType);
    }

    /**
     * 初始化bean时会执行该方法
     *
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        log.info("list:{}",list);
        for (QueryService queryService : list) {
            map.put(queryService.getClass().getSimpleName(), queryService);
        }
    }
    @Component
    class UserQueryImpl implements QueryService{

        @Override
        public boolean test1() {
            return false;
        }

        @Override
        public boolean test2() {
            return false;
        }
    }
    @Component
    class TeacherQueryImpl implements QueryService{
        @Override
        public boolean test1() {
            return true;
        }

        @Override
        public boolean test2() {
            return true;
        }
    }
}
